<template>
  <div id="userDetail">
    <Title
      :show-btn="false"
      :isShowBack="false"
      btn-name="保存"
      :name="fromData.id ? '应用编辑' : '新增应用'"
      @btnClick="saveForm('updataForm')"
    />
    <div class="basicBox">
      <el-form
        ref="updataForm"
        :rules="rules"
        label-position="right"
        label-width="80px"
        :model="fromData"
        size="mini"
        class="search_box"
      >
        <div class="row">
          <el-form-item label="应用名称" prop="applicationName">
            <el-input
              v-model.trim="fromData.applicationName"
              :validate-event="false"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="应用分类" prop="categoryId">
            <el-select v-model="fromData.categoryId" placeholder="请选择">
              <el-option
                v-for="dict in categoryList"
                :key="dict.id"
                :label="dict.categoryName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="IP地址" prop="address">
            <el-input
              v-model.trim="fromData.address"
              :validate-event="false"
              placeholder="请输入"
              @input="keyUP"
            />
          </el-form-item> -->
          <el-form-item class="oneRow" prop="orderNum" label="排序号">
            <el-input
              v-model.trim="fromData.orderNum"
              placeholder="请输入"
              type="number"
              :validate-event="false"
              @keydown.native="changeNumber"
            />
          </el-form-item>
          <el-form-item label="所属单位" prop="department">
            <el-input
              v-model.trim="fromData.department"
              :validate-event="false"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="联系电话" class="labelText" prop="phoneNum">
            <el-input
              v-model.trim="fromData.phoneNum"
              :validate-event="false"
              maxlength="11"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
          <!-- 除了联系人,电话,IP,其他都必填 -->
          <el-form-item class="labelText" label="联系人" prop="contactName">
            <el-input
              v-model.trim="fromData.contactName"
              :validate-event="false"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item class="labelText" label="是否启用" prop="deleteFlag">
            <el-radio-group v-model="fromData.deleteFlag">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 此为新增的字段 -->
          <el-form-item class="labelText" label="是否显示" prop="showFlag">
            <el-radio-group v-model="fromData.showFlag">
              <el-radio
                v-for="dict in showOptions"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="row">
          <el-form-item style="width: 643px" label="场景描述" prop="sceneDesc">
            <el-input
              style="width: 565px"
              v-model.trim="fromData.sceneDesc"
              :validate-event="false"
              type="textarea"
              :rows="5"
              placeholder="请输入"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="应用图标" class="labelIcon" prop="iconUrl">
            <div style="display: flex">
              <div class="imgBox" v-if="previewUrl || iconUrl">
                <img :src="previewUrl || iconUrl" class="previewImg" alt="" />
                <div class="del">
                  <i class="el-icon-delete" @click="delImg"></i>
                </div>
              </div>
              <div v-else>
                <upload @upload="imgUpload"></upload>
                <p class="hint">支持.png和.jpg格式,建议大小为72*72</p>
              </div>
            </div>
          </el-form-item>
        </div>
        <!-- <div class="row">
          <el-form-item label="应用图标" class="labelIcon" prop="iconUrl">
            <div style="display: flex">
              <div class="imgBox" v-if="previewUrl || iconUrl">
                <img :src="previewUrl || iconUrl" class="previewImg" alt="" />
                <div class="del">
                  <i class="el-icon-delete" @click="delImg"></i>
                </div>
              </div>
              <div v-else>
                <upload @upload="imgUpload"></upload>
                <p class="hint">支持.png和.jpg格式,建议大小为72*72</p>
              </div>
            </div>
          </el-form-item>
        </div> -->
        <div>
          <div class="addIP">
            <span>IP白名单</span
            ><el-input
              v-model.trim="ipAddress"
              :validate-event="false"
              placeholder="请输入"
              @input="keyUP"
              class="ipInput"
              size="mini"
            /><el-button size="mini" type="primary" @click="addIP"
              >添加</el-button
            >
          </div>
          <div style="height: 400px">
            <el-table
              :cell-style="getTdRowClass"
              :header-cell-style="getRowClass"
              :data="ipList"
              border
              style="width: 372px"
            >
              <el-table-column label="序号" type="index" width="50">
              </el-table-column>
              <el-table-column prop="name" label="IP地址"> </el-table-column>
              <el-table-column prop="address" label="操作" width="80">
                <template slot-scope="scope">
                  <div>
                    <el-button
                      type="text"
                      @click="deletIp(scope.row, scope.$index)"
                      >删除</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="btBox">
          <el-button size="mini" class="reset" @click="back()">取消</el-button>
          <el-button size="mini" type="primary" @click="saveForm('updataForm')"
            >保存</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import upload from "@/components/UploadImg/index.vue";
import { uploadImg } from "@/api/system/application_management";
import Title from "@/components/ShareTitle";
export default {
  components: {
    Title,
    upload,
  },
  props: {
    fromData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    categoryList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    id: {
      type: String,
      default: "",
    },
    iconUrl: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      ipAddress: "",
      ipList: [],
      previewUrl: undefined,
      statusOptions: [
        {
          value: 0,
          label: "启用",
        },
        {
          value: 1,
          label: "停用",
        },
      ],
      showOptions: [
        {
          value: 1,
          label: "显示",
        },
        {
          value: 0,
          label: "不显示",
        },
      ],
      count: 0,
      input: "",
      activeMenu: "",
      isClick: 1,
      rules: {
        applicationName: [
          { required: true, message: "应用名称不能为空", trigger: "blur" },
        ],
        sceneDesc: [
          { required: true, message: "场景描述不能为空", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择应用分类", trigger: "change" },
        ],
        orderNum: [
          { required: true, message: "排序号不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "IP地址不能为空", trigger: "blur" },
        ],
        department: [
          { required: true, message: "所属单位不能为空", trigger: "blur" },
        ],
      },
      fileBucket:
        process.env.NODE_ENV === "development"
          ? "ykm1-file-dev"
          : "ykm1-file-prod",
    };
  },
  mounted() {
    setTimeout(() => {
      var ipList = this.fromData.address.split(",");
      for (const i of ipList) {
        this.ipList.push({ name: i });
      }
    }, 1000);
  },
  methods: {
    keyUP() {
      this.ipAddress = this.ipAddress.replace(/[^\d^\.]+/g, "");
    },
    delImg() {
      this.previewUrl = "";
      this.iconUrl = "";
      this.fromData.iconUrl = "";
      this.imgFiles = "";
    },
    // 点击保存
    saveForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.fromData.phoneNum) {
            if (!/^1[3456789]\d{9}$/.test(this.fromData.phoneNum)) {
              this.$message.error("请输入正确的手机号");
              return false;
            }
          }
          if (this.ipList.length > 0) {
            var ipList = this.ipList.map((item) => {
              return item.name;
            });
            console.log(ipList, "ipListipListipList");
          }
          this.fromData.address = ipList.toString();
          if (this.fromData.orderNum === "0") {
            this.$message.error("排序值最小值为1");
            return false;
          }
          if (this.imgFiles) {
            const form = new FormData();
            form.append("file", this.imgFiles);
            form.append("bucket", this.fileBucket);
            var { data } = await uploadImg(form);
            this.fromData.iconUrl = data.fileName[0];
          }
          if (this.imgFiles === "" || this.fromData.iconUrl === "") {
            this.$message.error("请上传应用图标");
            return false;
          }
          if (this.fromData.id) {
            this.$emit("submit", JSON.stringify(this.fromData));
          } else {
            this.$emit("submit", JSON.stringify(this.fromData));
          }
        } else {
          return false;
        }
      });
    },
    imgUpload(e) {
      this.imgFiles = e.files[0];
      this.previewUrl = e.localUrls[0];
    },
    changeNumber(e) {
      // 不允许输入'e'和'.'以及'-'
      if (e.key === "e" || e.key === "." || e.key === "-" || e.key === "E") {
        e.returnValue = false;
        return false;
      }
    },
    // 添加IP
    addIP() {
      var str = this.ipAddress;
      var dotLength = str.split(".").length - 1; // 字符串中有多少个 .
      if (dotLength > 3 || dotLength < 3) {
        this.$message.error("请输入正确的IP地址");
        return false;
      }
      str = str.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/g);
      // console.log(str, "strstrstrstrstr");
      if (str === null) {
        this.$message.error("请输入正确的IP地址");
        return false;
      } else if (
        RegExp.$1 > 255 ||
        RegExp.$2 > 255 ||
        RegExp.$3 > 255 ||
        RegExp.$4 > 255
      ) {
        this.$message.error("请输入正确的IP地址");
        return false;
      } else {
        // alert("你输入的IP地址有效");
        // return true;
      }
      var ipNum = false;
      this.ipList.forEach((item) => {
        if (item.name[0] === this.ipAddress) {
          ipNum = true;
        }
      });
      if (ipNum) {
        this.$message.error("不能添加重复的IP地址");
        return false;
      }
      this.ipList.push({
        name: str,
      });
      this.ipAddress = "";
    },
    // 删除IP
    deletIp(row, index) {
      console.log(row, index, "row,index");
      this.$confirm(`确定要删除IP为${row.name}吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ipList.splice(index, 1);
          //点击确定的操作(调用接口)
        })
        .catch(() => {
          //取消的操作
        });
    },
    // 设置行样式
    getTdRowClass() {
      return "height:28px;padding:0";
    },
    // 设置表头背景颜色
    getRowClass() {
      return "background:#F5F6FA;color: #222;font-weight: 600;font-weight: 600;height:28px;padding:0";
    },
    back() {
      // this.closeView();
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding-top: 0px;
}
#userDetail {
  padding: 0px 20px 0px 20px;
}
.el-card__body {
  display: flex;
  flex-direction: column;
}
.basicBox {
  margin-top: 20px;
  .title {
    text-align: left;
    font-size: 16px;
    color: #222222;
    margin-bottom: 10px;
  }
  .search_box {
    .row {
      display: flex;
      flex-wrap: wrap;
    }
    .el-form-item--mini.el-form-item {
      margin-right: 40px;
    }
    ::v-deep.el-form-item--mini .el-form-item__label {
      text-align: left !important;
      color: #5d6470;
      font-size: 14px;
      font-weight: 400;
    }
    ::v-deep.el-form-item--mini .el-form-item__content {
      width: 220px;
    }
    ::v-deep.el-select > .el-input {
      width: 220px;
    }
    ::v-deep.el-input.is-disabled .el-input__inner {
      color: #222222;
    }
  }
}
::v-deep.oneRow .el-form-item__label {
  line-height: 20px !important;
}
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
.labelText {
  ::v-deep.el-form-item__label {
    &::before {
      content: "*";
      color: #ff4949;
      margin-right: 4px;
      opacity: 0;
    }
  }
}
.labelIcon {
  ::v-deep.el-form-item__label {
    &::before {
      content: "*";
      color: #ff4949;
      margin-right: 4px;
    }
  }
}
.btBox {
  text-align: right;
  margin-top: 10px;
}
.reset {
  background-color: #f3f4f6;
  color: #222222;
  border: none;
  height: 30px;
}
.reset.el-button:hover,
.reset.el-button:focus {
  background-color: #f3f4f6;
  color: #222222;
  border: none;
}
.imgBox {
  display: inline-block;
  position: relative;
  width: 104px;
  margin-right: 20px;
  min-height: 104px;
  .previewImg {
    width: 104px;
    height: 104px;
    margin-right: 20px;
  }
  .del {
    display: none;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 0px;
    right: 0px;
    text-align: center;
  }
  &:hover {
    .del {
      display: block;
    }
  }
  .el-icon-delete {
    font-size: 22px;
    color: #fff;
    margin-top: 40px;
  }
}
.hint {
  margin: 0;
  color: #828992;
  font-size: 12px;
}
.addIP {
  display: flex;
  margin-bottom: 20px;
  span {
    color: #5d6470;
    font-size: 14px;
    display: inline-block;
    height: 28px;
    line-height: 28px;
  }
  .ipInput {
    width: 220px;
    margin-left: 20px;
    margin-right: 20px;
  }
}
</style>
